﻿using System.IO;
using System.Text;
using System;

namespace DotNet.Common
{
    public class CommonFile
    {
        /// <summary>
        /// 修改原File.ReadAllText(string path)中Fileshare为Read而出现的异常
        /// </summary>
        /// <param name="filepath"></param>
        /// <returns></returns>
        public static string ReadAllText(string filepath)
        {
            if (string.IsNullOrEmpty(filepath))
                return string.Empty;

            Stream oStream = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 0x1000, FileOptions.SequentialScan);
            StreamReader oReader = new StreamReader(oStream, Encoding.UTF8);

            int num;
            char[] buffer = new char[0x1000];
            StringBuilder builder = new StringBuilder(0x1000);
            while ((num = oReader.Read(buffer, 0, buffer.Length)) != 0)
            {
                builder.Append(buffer, 0, num);
            }

            oReader.Close();
            oStream.Close();
            return builder.ToString();
        }

        public static string BuildDateTimeFilePath(string dirPath,string prefix, string extension)
        {
            try
            {
                Directory.CreateDirectory(dirPath);
            }
            catch
            {
                return string.Empty;
            }

            return Path.Combine(dirPath,string.Format(@"{0}{1}{2}",prefix,DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss"),extension));
        }
    }
}
